package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private HttpServletRequest request;



    @Autowired
    JwtProperties jwtProperties;




    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO)  {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw  new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码MD5加密需要做加密或者解密
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());


        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        //非管理员账户
        if (!encryptedPassword.equals(employee.getPassword()) && !"admin".equals(employee.getUsername()) ) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

//        //管理员账户
//        if (!encryptedPassword.equals(DigestUtils.md5DigestAsHex(password.getBytes())) && "admin".equals(employee.getUsername())) {
//            //密码错误
//            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
//        }

        //0  1 状态码
        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }



    /**
     * 新增员工
     * @param employeeDTO
     */
    @Override
    public void insertEmp(EmployeeDTO employeeDTO) {
//        int i=1/0;
        Employee employee=new Employee();

        //beanUtile 对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);

        //属性设置
        //    private String password;
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));



        //    private Integer status;
        employee.setStatus(StatusConstant.ENABLE);


        //    private LocalDateTime createTime;
        employee.setCreateTime(LocalDateTime.now());

        //    private LocalDateTime updateTime;
        employee.setUpdateTime(LocalDateTime.now());

        //3  处理操作人
//        String token = request.getHeader("token");
//        Claims claims = JwtUtil.parseJWT( jwtProperties.getAdminSecretKey(),token);
//        //登录的人做操作人
//        Integer empId = (Integer) claims.get("empId");

        log.info("ThreadLocal :"+ BaseContext.getCurrentId());
        //令牌的拦截器方法以将登录用户的id存储到当前线程的ThreadLocal中
        // TODO 需要改为当前用的id
        //private Long createUser;
        employee.setCreateUser(BaseContext.getCurrentId());


        // TODO 需要改为当前用的id
        //private Long updateUser;
        employee.setUpdateUser( BaseContext.getCurrentId());



        employeeMapper.insertEmp(employee);
    }

    /**
     *根据id查员工
     */
    @Override
    public Result getById(Long id) {
        Employee emp = employeeMapper.getById(id);
        return Result.success(emp);
    }

    /**
     * 分页查询
     * @param pageQueryDTO
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO pageQueryDTO) {
        if(pageQueryDTO.getPage()<=0){
            pageQueryDTO.setPage(1);
        }
        if(pageQueryDTO.getPageSize()<=0){
            pageQueryDTO.setPageSize(10);
        }

        //设置分页参数
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());

        //员工列表查询
        List<Employee> employeeList = employeeMapper.pageQuery(pageQueryDTO);

        Page page= (Page) employeeList;

        return new PageResult(page.getTotal(),page.getResult());
    }


    /**
     * 修改状态 根据员工id
     * @param status
     * @param empId
     * @return
     */
    @Override
    public Result updateStatus(Integer status, Long empId) {
        Employee employee=new Employee();
        employee.setUpdateUser(BaseContext.getCurrentId());
        employee.setId(empId);
        employee.setStatus(status);
        employee.setUpdateTime(LocalDateTime.now());


        //修改返回影响的行数
        Integer result = employeeMapper.updateStatus(employee);


        return Result.success();
    }


    /**
     * 员工信息修改
     * @param employeeDTO
     */
    @Override
    public Result putEmpInfo(EmployeeDTO employeeDTO) {
        Employee employee =new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
//        employee.setUpdateUser(BaseContext.getCurrentId());
//        employee.setUpdateTime(LocalDateTime.now());
        employeeMapper.putEmpInfo(employee);
        return Result.success();
    }

    /**
     * 修改密码
     * @param passwordEditDTO
     * @return
     */

    @Override
    public Result putPwd(PasswordEditDTO passwordEditDTO) {
        Employee employee =new Employee();
        BeanUtils.copyProperties(passwordEditDTO,employee);
//        passwordEditDTO.setEmpId(BaseContext.getCurrentId());
        employeeMapper.putPwd(employee);
        return Result.success();
    }
}
